<template>
  <button @click="state.isshow = !state.isshow,openCamera()">dakai</button>
  <button id="stopVideo" @click="stopVideo">关闭摄像头</button>
  <button id="stopVideo" @click="checkImg">选择图片</button>
  <button @click="setImage">sss</button>
  <view class="content" v-show="state.isshow">
    <div id="container">
      <video id="video-local" autoplay playsinline></video>
      <!-- <button id="showVideo">打开摄像头</button>
      <button id="stopVideo">关闭摄像头</button> -->
      <!-- <button @click="setImage">sss</button> -->
      <p>显示摄像头预览的内容，网页上由元素video来呈现。</p>
      <p>点击打开摄像头按钮后，浏览器会询问是否允许，请点击“允许”。</p>
      <div id="errorMsg"></div>
      <div id="tipMsg"></div>
      <canvas id="canvas"></canvas>
    </div>
  </view>
</template>

<script setup>
import { reactive, getCurrentInstance, onMounted, ref } from "vue";
import { setAuthorization, getAuthorization } from "@/utils/auth.js";
import { onLoad } from "@dcloudio/uni-app";

const state = reactive({
  isshow:false
})


const checkImg = () => {
  uni.chooseImage({
	count: 6, //默认9
	sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
	sourceType: ['album'], //从相册选择
	success: function (res) {
		console.log(res);
	}
});
}

const constraints = (window.constraints = {
  audio: false,
  video: true,
});
function showErrMsg(msg, error) {
  const errorElement = document.querySelector("#errorMsg");
  errorElement.innerHTML += `<p>${msg}</p>`;
  if (typeof error !== "undefined") {
    console.error(error);
  }
}

function showMsg(msg) {
  const msgEle = document.querySelector("#tipMsg");
  msgEle.innerHTML += `<p>-> ${msg}</p>`;
  console.log(msg);
}
let videoEle = null;

function gotStream(stream) {
  videoEle = document.querySelector("video");
  const videoTracks = stream.getVideoTracks();
  showMsg(`正在使用的设备: ${videoTracks[0].label}`);
  window.stream = stream;
  videoEle.srcObject = stream;
  // setInterval(() => {
  //   setImage()
  // },2000)
}

function stopVideo(e) {
  showMsg("停止视频");
  const videoElem = document.querySelector("video");
  const stream = videoElem.srcObject;

  // document.querySelector("#showVideo").disabled = false; // 允许开启

  if (stream == null) {
    return;
  }
  const tracks = stream.getTracks();

  tracks.forEach(function (track) {
    track.stop();
  });
  videoElem.srcObject = null;
}

async function openCamera(e) {
  try {
    showMsg("正在打开摄像头");
    const stream = await navigator.mediaDevices.getUserMedia(constraints);
    showMsg("获取到了stream");
    gotStream(stream);
    e.target.disabled = true;
  } catch (err) {
    // onErr(err);
  }
}

const parseBlob = (base64) => {
  console.log(base64)
  let arr = base64.split(",");
  let mime = arr[0].match(/:(.*?);/)[1];
  let bstr = atob(arr[1]);
  let n = bstr.length;
  let u8arr = new Uint8Array(n);
  for (let i = 0; i < n; i++) {
    u8arr[i] = bstr.charCodeAt(i);
  }
  let url = URL || webkitURL;
  let a = new Blob([u8arr], { type: mime });
  let file2 = new File([a], "test.jpg", { type: "image/jpg" });
  console.log(URL.createObjectURL(a),file2);
};

const setImage = () => {
  videoEle.setAttribute("crossOrigin", "anonymous"); // 处理跨域，H5需后台支持，请求的视频资源响应投标需有Access-Control-Allow-Origin
  // videoEle.setAttribute("src", url);
  videoEle.setAttribute("width", 400);
  videoEle.setAttribute("height", 400);
  videoEle.setAttribute("preload", "auto");
  let canvas = document.createElement("canvas");
  let width = videoEle.width; // canvas的尺寸和图片一样
  let height = videoEle.height;
  canvas.width = width;
  canvas.height = height;
  canvas.getContext("2d").drawImage(videoEle, 0, 0, width, height); // 绘制canvas
  console.log(canvas)
  const dataURL = canvas.toDataURL("image/jpg"); // 转换为base64
  // console.log(dataURL);
  parseBlob(dataURL);
};

const handleSubmit = () => {
    var blob = new Blob(state.recordedBlobs, { type: "iamge/jpg" });
    var reader = new FileReader();
    reader.readAsDataURL(blob, "utf-8");
    reader.onload = () => {
      let str = base64toFile(reader.result);
      let formData = new FormData();
      formData.append("file", str);
      uploadVideo(formData);
    };
  };

onMounted(() => {
});
</script>

<style lang="scss" scoped>
.content {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(255, 255, 255, 0.4);
  backdrop-filter: blur(130px);

  .login-image {
    margin-top: -200rpx;
    display: flex;
    justify-content: center;
  }

  .login-image-text {
    margin-top: 15rpx;
    text-align: center;
    font-weight: 700;
    font-size: 32rpx;
    line-height: 150%;
    color: #223263;
  }
}

.login-form {
  margin-top: 20px;
}

.unilogin-form-item {
  display: flex;
  width: calc(100vw - 40rpx);
  border: 2rpx solid #f2f2f2;
  background: #fff;
  align-items: center;
  padding: 10rpx 20rpx;
  box-sizing: border-box;
  margin-bottom: 20rpx;
  border-radius: 10rpx;

  .login-item-input {
    width: 100%;
    margin-left: 10rpx;
    height: 72rpx;
    line-height: 72rpx;
    padding: 0;
    font-size: 60rpx;
  }
}

::v-deep .van-field__control {
  font-size: 32rpx;
  height: 72rpx;
  line-height: 72rpx;
}

.column1 {
  border: 2rpx solid #2596d7 !important;
  color: #2596d7;
}

.van-button {
  height: 120rpx;
  background: radial-gradient(125% 125% at 85.42% 0%, #85d3ff 0%, #2596d7 100%);
  border-radius: 8px;
  font-style: normal;
  font-weight: 600;
  font-size: 36rpx;
  color: #fff;
  border: none;
}

input {
  -webkit-tap-highlight-color: rgba(255, 255, 255, 0);
  -webkit-user-select: none;
  -moz-user-focus: none;
  -moz-user-select: none;
  -webkit-appearance: none;
  outline: none;
  border: none;
}
:deep(.uni-video-cover) {
  display: none !important;
}
:deep(.uni-video-bar) {
  display: none !important;
}
#video-local {
  position: fixed;
  top:0;
  left:0;
  width: 100vw;
  height: 100vh;
  transform: scaleX(-1);
}
</style>
